layui.use(['form', 'table', 'laydate', 'element'], function(){
    var table = layui.table;
    var form = layui.form;
    var laydate = layui.laydate;
    var element = layui.element;
    const ajaxDeliveryList = "/general/guojigang/public/index/delivery/ajaxList";
    const addData1 = "/general/guojigang/public/index/delivery/addData1";
    const addData2 = "/general/guojigang/public/index/delivery/addData2";
    const ajaxChangeList = "/general/guojigang/public/index/delivery/ajaxChangeList";
    const ajaxVerifyList = "/general/guojigang/public/index/delivery/ajaxVerifyList";
    const doVerify = "/general/guojigang/public/index/delivery/doVerify";
    const nodeList = "/general/guojigang/public/index/delivery/nodeList";
    const logUrl = "/general/guojigang/public/index/delivery/logList";
    

    // var data = [];
    // var addedArray = [];
    table.render({
        elem: '#delivery_list1'
        ,url: ajaxDeliveryList + '?type=1'
        ,limits: [10,20,50,100,200,500,1000,99999]
        ,limit: 20 //每页默认显示的数量
        ,response: {
            statusName: 'status'
            ,statusCode: 200
            ,msgName: 'msg'
            ,countName: 'count'
            ,dataName: 'data'
        }
        ,cols: [[
            {toolbar:'#colDeliveryBar', width:'100'}
            ,{field:'id', title: 'ID', sort: true, width:'100'}
            ,{field:'deliveryDate', title: '交期变更', hide: 'true'}
            ,{
              field:'isShow',
              title: '订单状态',
              width: '120',
              sort: true,
              templet: function (d) {
                var state = "";
                if (d.isShow == 1) {
                    state = "<strong style='color:#009688'>开启</strong>";
                }
                else {
                    state = "<strong style='color:red'>关闭</strong>";
                }
                return state;
              }
            }
            ,{field:'orderId', title: '订单ID', width:'100', sort: true}
            ,{field:'orderNo', title: '订单编号', width:'250', sort: true}
            ,{field:'ddLeiXing', title: '订单类型', width:'100', sort: true}
            ,{field:'zhangtao', title: '账套', width:'200', sort: true}
            ,{field:'currency', title: '币种', width:'100', sort: true}
            ,{field:'cCusName', title: '客户名称', width:'260', sort: true}
            ,{field:'date1', title: '目标交期', width:'150', sort: true}
            ,{field:'date2', title: '确认交期', width:'150', sort: true}
            ,{field:'cCusPPersonText', title: '业务员', width:'100', sort: true}
            ,{field:'atTime', title: '送达时间', width:'200', sort: true}
            ,{field: 'record', title: '', templet:'#record1', width:'100'}
        ]]
        ,id: 'delivery_list1'
        ,page: true
        ,toolbar:"#headDeliveryBar"
        ,text: { none: '暂无相关数据' }
        ,totalRow:true
        ,done: function (res, curr, count){
          //  $("[data-field='orderId']").css('display','none');
           $("[data-field='deliveryDate']").css('display','none');

           $(".layui-table tr").each(function(){
                //已选择的按钮灰度掉
                var text = $(this).children("td:nth-child(2)").text();
                text = parseInt(text);
                var obj_array = layui.data('jiaoqibg').obj_key;
                if ( Array.isArray(obj_array)) {
                  obj_array.forEach(element => {
                    if(element.id == text){
                      $(this).children("td:first").find('button').addClass("layui-btn-disabled").attr("disabled",true);
                    }
                  });
                }
                
          })

          table.render({
            elem: '#add_list'
            ,data: layui.data('jiaoqibg').obj_key
            ,cols: [[
                {toolbar:'#colDeliveryAddBar',width:'100'}
                ,{field:'deliveryDate', title: '交期变更',event:'cellClick', width:'160'}
                ,{
                  field:'isShow',
                  title: '订单状态',
                  templet: function (d) {
                    var state = "";
                    if (d.isShow == 1) {
                        state = "<input type='checkbox' value='" + d.id + "' id='isShow' lay-filter='stat1' checked='checked' name='isShow'  lay-skin='switch' lay-text='开启|关闭' >";
                    }
                    else {
                        state = "<input type='checkbox' value='" + d.id + "' id='isShow' lay-filter='stat1'  name='isShow'  lay-skin='switch' lay-text='开启|关闭' >";
                    }
                    return state;
                  },
                  width:'120'
                }
                ,{field:'orderId', title: '订单ID', width:'100'}
                ,{field:'orderNo', title: '订单编号', width:'250'}
                ,{field:'ddLeiXing', title: '订单类型', width:'100'}
                ,{field:'zhangtao', title: '账套', width:'200'}
                ,{field:'currency', title: '币种', width:'100'}
                ,{field:'cCusName', title: '客户名称', width:'260'}
                ,{field:'date1', title: '目标交期', width:'150'}
                ,{field:'date2', title: '确认交期', width:'150'}
                ,{field:'cCusPPersonText', title: '业务员', width:'100'}
                ,{field:'atTime', title: '送达时间', width:'200'}
            ]]
            ,id: 'add_list'
            ,page: true
            ,done:function(){
            }
            ,text: { none: '暂无相关数据' }
          });
                    
        }
    });

    //2 进入页面直接渲染
    table.render({
      elem: '#delivery_list2'
      ,url: ajaxDeliveryList +'?type=2'
      ,limits: [10,20,50,100,200,500,1000,99999]
      ,limit: 20 //每页默认显示的数量
      ,response: {
          statusName: 'status'
          ,statusCode: 200
          ,msgName: 'msg'
          ,countName: 'count'
          ,dataName: 'data'
      }
      ,cols: [[
        {toolbar:'#colDeliveryBar', width:'100'}
        ,{field:'id', title: 'ID', width:'100'}
        ,{field:'deliveryDate', title: '交期变更', hide: 'true'}
        ,{
          field:'isShow',
          title: '订单状态',
          width: '160',
          templet: function (d) {
            var state = "";
            if (d.isShow == 1) {
              state = "<strong style='color:#009688'>开启</strong>";
            }
            else {
              state = "<strong style='color:red'>关闭</strong>";
            }
            return state;
          }
        }
        ,{field:'orderId', title: '订单ID', width:'100'}
        ,{field:'orderNo', title: '订单编号', width:'250'}
        ,{field:'ddLeiXing', title: '订单类型', width:'100'}
        ,{field:'zhangtao', title: '账套', width:'200'}
        ,{field:'currency', title: '币种', width:'100'}
        ,{field:'cCusName', title: '客户名称', width:'260'}
        ,{field:'date1', title: '目标交期', width:'150'}
        ,{field:'date2', title: '确认交期', width:'150'}
        ,{field:'cCusPPersonText', title: '业务员', width:'100'}
        ,{field:'atTime', title: '送达时间', width:'200'}
        ,{field: 'record', title: '', templet:'#record1', width:'100'}
      ]]
      ,id: 'delivery_list2'
      ,page: true
      ,toolbar:"#headDeliveryBar"
      ,text: { none: '暂无相关数据' }
      ,totalRow:true
      ,done: function (res, curr, count){
        //  $("[data-field='orderId']").css('display','none');
         $("[data-field='deliveryDate']").css('display','none');

         $(".layui-table tr").each(function(){
              //已选择的按钮灰度掉
              var text = $(this).children("td:nth-child(2)").text();
              text = parseInt(text);
              var obj_array = layui.data('jiaoqibg2').obj_key;
              if (Array.isArray(obj_array)) {
                obj_array.forEach(element => {
                  if(element.id == text){
                    $(this).children("td:first").find('button').addClass("layui-btn-disabled").attr("disabled",true);
                  }
                });
              }
        })

        table.render({
          elem: '#add_list2'
          ,data: layui.data('jiaoqibg2').obj_key
          ,cols: [[
              {toolbar:'#colDeliveryAddBar',  width:'100'}
              ,{field:'deliveryDate', title: '交期变更',event:'cellClick2', width:'160'}
              ,{
                field:'isShow',
                title: '订单状态',
                templet: function (d) {
                  var state = "";
                  if (d.isShow == 1) {
                      state = "<input type='checkbox' value='" + d.id + "' id='isShow' lay-filter='stat2' checked='checked' name='isShow'  lay-skin='switch' lay-text='开启|关闭' >";
                  }
                  else {
                      state = "<input type='checkbox' value='" + d.id + "' id='isShow' lay-filter='stat2'  name='isShow'  lay-skin='switch' lay-text='开启|关闭' >";
                  }
                  return state;
                },
                width:'160'
              }              
              ,{field:'orderId', title: '订单ID', width:'100'}
              ,{field:'orderNo', title: '订单编号', width:'250'}
              ,{field:'ddLeiXing', title: '订单类型', width:'100'}
              ,{field:'zhangtao', title: '账套', width:'200'}
              ,{field:'currency', title: '币种', width:'100'}
              ,{field:'cCusName', title: '客户名称', width:'260'}
              ,{field:'date1', title: '目标交期', width:'150'}
              ,{field:'date2', title: '确认交期', width:'150'}
              ,{field:'cCusPPersonText', title: '业务员', width:'100'}
              ,{field:'atTime', title: '送达时间', width:'200'}
          ]]
          ,id: 'add_list2'
          ,page: true
          ,done:function(){
          }
          ,text: { none: '暂无相关数据' }
        });
                  
      }
    });

    table.on('toolbar(user)', function (obj) {
        switch(obj.event){
            case 'batch_verify':
                var num = 0;
                var selectData = layui.table.checkStatus('verify_list').data; //勾选内容
                if (selectData.length == 0){
                    layer.msg('请至少选择一项');
                    return false;
                }
                let idArr = [];
                for (let i=0; i<selectData.length; i++){
                  idArr.push(selectData[i].verify_id);
                }
                let idStr = idArr.join(',');
                console.log(obj.data);
                layer.open({
                  //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                  type:1,
                  title:"审核订单",
                  btn: ['通过','不通过'], 
                  success:function(){
                      // $("#chbm_code").val(obj.data.code);                        
                  },
                  yes: function (index, layero) {
                    layer.confirm('确定审核<strong style="color:#009688">通过</strong>?', function(index){
                      let para = {
                        id:idStr, 
                        status:2
                      };
                      num += 1;
                      if (num == 1) {
                        $.ajax({
                          type: "POST",
                          url: doVerify,
                          data: para,
                          traditional: true, //是否使用传统的方式浅层序列化,若有数组参数或对象参数需要设置true!!!!!!
                          dataType:"json",
                          success: function(returnData){                            
                              if(returnData.status == 200){
                                  layer.alert(returnData.msg, {
                                      closeBtn: 0
                                    }, function(){
                                        layer.close(layer.index);
                                        table.reload('verify_list',{}) 
                                    });
                              }else{
                                  layer.alert(returnData.msg, {
                                      closeBtn: 0
                                    }, function(){
                                      layer.close(layer.index);
                                    });
                              }
                          }
                        })
                      }
                    })  
                    layer.close(index);
                  }
                  ,btn2: function(index, layero){
                    layer.confirm('确定审核<strong style="color:red">不通过</strong>?', function(index){
                      let para = {
                        id:idStr, 
                        status:3
                      };
                      num += 1;
                      if (num == 1) {
                        $.ajax({
                          type: "POST",
                          url: doVerify,
                          data: para,
                          traditional: true, //是否使用传统的方式浅层序列化,若有数组参数或对象参数需要设置true!!!!!!
                          dataType:"json",
                          success: function(returnData){                            
                              if(returnData.status == 200){
                                  layer.alert(returnData.msg, {
                                      closeBtn: 0
                                    }, function(){
                                      layer.close(layer.index);   
                                      table.reload('verify_list',{}) 
                                    });
                              }else{
                                  layer.alert(returnData.msg, {
                                      closeBtn: 0
                                    }, function(){
                                      layer.close(layer.index);
                                    });
                              }
                          }
                        })
                      }
                    })
                  }
                });
                break;
        }
    })

    table.on('tool(user)', function(obj){
        switch(obj.event){
            case 'add':
                $(this).addClass("layui-btn-disabled").attr("disabled",true);
                if (layui.data('jiaoqibg').obj_key == undefined) {
                    layui.data('jiaoqibg', {key:'obj_key', value:[]});
                    var obj_data = layui.data('jiaoqibg').obj_key;
                    obj_data.push(obj.data);
                    //更新操作
                    layui.data('jiaoqibg', {key:'obj_key', value: obj_data});
                } else {
                      var obj_data = layui.data('jiaoqibg').obj_key;
                      obj_data.push(obj.data);
                      //更新操作
                      layui.data('jiaoqibg', {key:'obj_key', value: obj_data});
                }

                //添加的数据项
                table.render({
                  elem: '#add_list'
                  ,data: layui.data('jiaoqibg').obj_key
                  ,cols: [[
                      {toolbar:'#colDeliveryAddBar', width:'100'}
                      ,{field:'deliveryDate', title: '交期变更',event:'cellClick', width:'150'}
                      ,{
                        field:'isShow',
                        title: '状态',
                        width:'160',
                        templet: function (d) {
                          var state = "";
                          if (d.isShow == 1) {
                              state = "<input type='checkbox' value='" + d.id + "' id='isShow' lay-filter='stat1' checked='checked' name='isShow'  lay-skin='switch' lay-text='开启|关闭' >";
                          }
                          else {
                              state = "<input type='checkbox' value='" + d.id + "' id='isShow' lay-filter='stat1'  name='isShow'  lay-skin='switch' lay-text='开启|关闭' >";
                          }
                          return state;
                        }
                      }
                      ,{field:'orderId', title: '订单ID', width:'100'}
                      ,{field:'orderNo', title: '订单编号', width:'250'}
                      ,{field:'ddLeiXing', title: '订单类型', width:'100'}
                      ,{field:'zhangtao', title: '账套', width:'200'}
                      ,{field:'currency', title: '币种', width:'100'}
                      ,{field:'cCusName', title: '客户名称', width:'260'}
                      ,{field:'date1', title: '目标交期', width:'150'}
                      ,{field:'cCusPPersonText', title: '业务员', width:'100'}
                      ,{field:'atTime', title: '送达时间', width:'150'}
                  
                  ]]
                  ,id: 'add_list'
                  ,page: true
                  ,done:function(){
                  }
                  ,text: { none: '暂无相关数据' }
                });
                break;
            case 'del':
                var num2 = $(obj.tr).attr("data-index");
                var obj_data = layui.data('jiaoqibg').obj_key;
                obj_data.splice(num2,1);
                layui.data('jiaoqibg', {key:'obj_key', value: obj_data});
                //更新操作
                // layui.data('addindex', {key:'index_key', value: index_data});
                layer.confirm('确定删除?', {icon: 3, title: '提示'}, function (index) {
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    layer.close(index);
                    table.reload('delivery_list1', {
                        page: {
                          curr: 1 //重新从第 1 页开始
                        }
                    })
                });
                break;
            case 'add2':
            $(this).addClass("layui-btn-disabled").attr("disabled",true);
            if (layui.data('jiaoqibg2').obj_key == undefined) {
                layui.data('jiaoqibg2', {key:'obj_key', value:[]});
                var obj_data = layui.data('jiaoqibg2').obj_key;
                obj_data.push(obj.data);
                //更新操作
                layui.data('jiaoqibg2', {key:'obj_key', value: obj_data});
            } else {
                  var obj_data = layui.data('jiaoqibg2').obj_key;
                  obj_data.push(obj.data);
                  //更新操作
                  layui.data('jiaoqibg2', {key:'obj_key', value: obj_data});
            }
            //添加的数据项
            table.render({
              elem: '#add_list2'
              ,data: layui.data('jiaoqibg2').obj_key
              ,cols: [[
                  {toolbar:'#colDeliveryAddBar', width:'100'}
                  ,{field:'deliveryDate', title: '交期变更',event:'cellClick2', width:'150'}
                  ,{
                    field:'isShow',
                    title: '订单状态',
                    templet: function (d) {
                      var state = "";
                      if (d.isShow == 1) {
                          state = "<input type='checkbox' value='" + d.id + "' id='isShow' lay-filter='stat2' checked='checked' name='isShow'  lay-skin='switch' lay-text='开启|关闭' >";
                      }
                      else {
                          state = "<input type='checkbox' value='" + d.id + "' id='isShow' lay-filter='stat2'  name='isShow'  lay-skin='switch' lay-text='开启|关闭' >";
                      }
                      return state;
                    },
                    width:'160'
                  }                  
                  ,{field:'orderId', title: '订单ID', width:'100'}
                  ,{field:'orderNo', title: '订单编号', width:'250'}
                  ,{field:'ddLeiXing', title: '订单类型', width:'100'}
                  ,{field:'zhangtao', title: '账套', width:'200'}
                  ,{field:'currency', title: '币种', width:'100'}
                  ,{field:'cCusName', title: '客户名称', width:'260'}
                  ,{field:'date1', title: '目标交期', width:'150'}
                  ,{field:'cCusPPersonText', title: '业务员', width:'100'}
                  ,{field:'atTime', title: '送达时间', width:'150'}
              
              ]]
              ,id: 'add_list2'
              ,page: true
              ,done:function(){
              }
              ,text: { none: '暂无相关数据' }
            });
            break;
            case 'del2':
                var num2 = $(obj.tr).attr("data-index");
                var obj_data = layui.data('jiaoqibg2').obj_key;
                obj_data.splice(num2,1);
                layui.data('jiaoqibg2', {key:'obj_key', value: obj_data});
                layer.confirm('确定删除?', {icon: 3, title: '提示'}, function (index) {
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    layer.close(index);
                    table.reload('delivery_list2', {
                        page: {
                          curr: 1 //重新从第 1 页开始
                        }
                    })
                });
                break;
            case 'verify':
              var num = 0;
              layer.open({
                //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                type:1,
                title:"审核订单",
                btn: ['通过','不通过'], 
                success:function(){
                    // $("#chbm_code").val(obj.data.code);                        
                },
                yes: function (index, layero) {
                  layer.confirm('确定审核<strong style="color:#009688">通过</strong>?', function(index){
                    let para = {
                      id:obj.data.verify_id, 
                      status:2
                    };
                    num += 1;
                    if (num == 1) {
                      $.ajax({
                        type: "POST",
                        url: doVerify,
                        data: para,
                        traditional: true, //是否使用传统的方式浅层序列化,若有数组参数或对象参数需要设置true!!!!!!
                        dataType:"json",
                        success: function(returnData){                            
                            if(returnData.status == 200){
                                layer.alert(returnData.msg, {
                                    closeBtn: 0
                                  }, function(){
                                      let data = obj.data;
                                      data.status = 2;
                                      obj.update(obj.data);
                                      layer.close(layer.index);
                                      table.reload('verify_list',{}) 
                                  });
                            }else{
                                layer.alert(returnData.msg, {
                                    closeBtn: 0
                                  }, function(){
                                    layer.close(layer.index);
                                  });
                            }
                        }
                      })
                    }
                  })  
                  layer.close(index);
                }
                ,btn2: function(index, layero){
                  layer.confirm('确定审核<strong style="color:red">不通过</strong>?', function(index){
                    let para = {
                      id:obj.data.verify_id, 
                      status:3
                    };
                    num += 1;
                    if (num == 1) {
                      $.ajax({
                        type: "POST",
                        url: doVerify,
                        data: para,
                        traditional: true, //是否使用传统的方式浅层序列化,若有数组参数或对象参数需要设置true!!!!!!
                        dataType:"json",
                        success: function(returnData){                            
                            if(returnData.status == 200){
                              
                              console.log(obj);
                              obj.update({
                                status:3
                              });
                              console.log(obj.tr.find('td[data-field=status]'));  
                                layer.alert(returnData.msg, {
                                    closeBtn: 0
                                  }, function(){
                                    let data = obj.data;
                                    data.status = 3;
                                    obj.update(obj.data);
                                    layer.close(layer.index);   
                                    table.reload('verify_list',{}) 
                                  });
                            }else{
                                layer.alert(returnData.msg, {
                                    closeBtn: 0
                                  }, function(){
                                    layer.close(layer.index);
                                  });
                            }
                        }
                      })
                    }
                    
                  })
                  //return false 开启该代码可禁止点击该按钮关闭
                }
              });
              break;
            case 'view':
              layer.open({
                type:2,
                title:'流程步骤',
                area:['50%','70%'],
                content:nodeList + '?id=' + obj.data.delivery_id,
                success: function(obj, index){
                    form.render();
                }
              });
              break;
            case 'view2':
            layer.open({
              type:2,
              title:'流程步骤',
              area:['50%','70%'],
              content:nodeList + '?id=' + obj.data.delivery_id + '&change=1',
              success: function(obj, index){
                  form.render();
              }
            });
              break;
            case 'cellClick':
              var field = $(this).data('field');
              if (!obj.data.isShow){
                layer.alert("请开启此订单！！");
                return false;
              } 
              var date1 = laydate.render({
                  elem: this.firstChild,
                  show: true,
                  min:minDate(),
                  closeStop: this,  //这里代表的意思是：点击 this 所在元素阻止关闭事件冒泡。如果不设定，则无法弹出控件<br>　　
                  done: function (value, res) {
                      var obj_data = layui.data('jiaoqibg').obj_key;
                      //当前行数据
                      var data = obj.data;
                      obj_data.forEach(item=>{
                        if(item.id==data.id){
                            data[field] = value;
                            item[field] = value;
                        }
                      })
                      obj.update(data);
                      table.reload('add_list',{}) 
                      //更新操作
                      layui.data('jiaoqibg', {key:'obj_key', value: obj_data});
                  }
                });
              break;
            case 'cellClick2':
            var field = $(this).data('field'); 
            if (!obj.data.isShow){
              layer.alert("请开启此订单！！");
              return false;
            }
            var date1 = laydate.render({
                elem: this.firstChild,
                show: true,
                min:minDate(),
                closeStop: this,  //这里代表的意思是：点击 this 所在元素阻止关闭事件冒泡。如果不设定，则无法弹出控件<br>　　
                done: function (value, res) {
                    var obj_data = layui.data('jiaoqibg2').obj_key;
                    //当前行数据
                    var data = obj.data;
                    obj_data.forEach(item=>{
                      if(item.id==data.id){
                          data[field] = value;
                          item[field] = value;
                      }
                    })
                    obj.update(data); 
                    table.reload('add_list2',{}) 
                    //更新操作
                    layui.data('jiaoqibg2', {key:'obj_key', value: obj_data});
                }
              });
              break;
            //变更明细销售->计划
            case 'change_detail':
              layer.open({
                //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                type:2,
                title:'变更日志',
                area:['700px','300px'],
                content:logUrl + '?ticket_no=' + obj.data.orderId + '&action_type=4&type=1',
                success: function(obj, index){
                    console.log(obj);
                    form.render();
                }
            });
              break;
            //变更明细计划->销售
            case 'change_detail2':
              layer.open({
                //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                type:2,
                title:'变更日志',
                area:['700px','300px'],
                content:logUrl + '?ticket_no=' + obj.data.orderId + '&action_type=4&type=2',
                success: function(obj, index){
                    console.log(obj);
                    form.render();
                }
            });
              break;
            //变更明细审核变更
            case 'change_detail3':
            layer.open({
              //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
              type:2,
              title:'变更日志',
              area:['700px','300px'],
              content:logUrl + '?ticket_no=' + obj.data.delivery_id + '&action_type=3',
              success: function(obj, index){
                  console.log(obj);
                  form.render();
              }
            });
              break;
            //变更明细修改审核员变更
            case 'change_detail4':
            layer.open({
              //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
              type:2,
              title:'变更日志',
              area:['700px','300px'],
              content:logUrl + '?ticket_no=' + obj.data.id + '&action_type=5',
              success: function(obj, index){
                  console.log(obj);
                  form.render();
              }
            });
              break;
            case 'do_it':
              var num = 0;
              $("#orderNo").val(obj.data.orderNo);
              $("#zhangtao").val(obj.data.zhangtao);
              $("#orderType").val(obj.data.ddLeiXing);
              $("#productCategory").val(obj.data.categories);
              $("#country").val(obj.data.country);
              $("#customerAbb").val(obj.data.customer);
              $("#bgrq").val(obj.data.ctime);
              $("#publisher").val(obj.data.username);
              $("#businessman").val(obj.data.cCusPPersonText);
              $("#oldjq").val(obj.data.date2);
              $("#newjq").val(obj.data.delivery_date);
              let oldIsShow = obj.data.oldIsShow ? "开启" : "关闭";
              let newIsShow = obj.data.isShow ? "开启" : "关闭";
              $("#oldOrderStatus").val(oldIsShow);
              $("#newOrderStatus").val(newIsShow);
              layer.open({
                type: 1,
                area:['400px','850px'],
                content: $('#orderInfo'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                btn: ['通过', '不通过', '关闭']
                ,yes: function(index, layero){
                  layer.confirm('确定审核<strong style="color:#009688">通过</strong>?', function(index){
                    let para = {
                      id:obj.data.verify_id, 
                      status:2
                    };
                    num += 1;
                    if (num == 1) {
                      $.ajax({
                        type: "POST",
                        url: doVerify,
                        data: para,
                        traditional: true, //是否使用传统的方式浅层序列化,若有数组参数或对象参数需要设置true!!!!!!
                        dataType:"json",
                        success: function(returnData){                            
                            if(returnData.status == 200){
                                layer.alert(returnData.msg, {
                                    closeBtn: 0
                                  }, function(){
                                    layer.closeAll();  
                                      table.reload('verify_list',{}) 
                                  });
                            }else{
                                layer.alert(returnData.msg, {
                                    closeBtn: 0
                                  }, function(){
                                    layer.closeAll();  
                                  });
                            }
                        }
                      })
                    }
                  })  
                  //按钮【按钮一】的回调
                }
                ,btn2: function(index, layero){
                  layer.confirm('确定审核<strong style="color:red">不通过</strong>?', function(index){
                    let para = {
                      id:obj.data.verify_id, 
                      status:3
                    };
                    num += 1;
                    if (num == 1) {
                      $.ajax({
                        type: "POST",
                        url: doVerify,
                        data: para,
                        traditional: true, //是否使用传统的方式浅层序列化,若有数组参数或对象参数需要设置true!!!!!!
                        dataType:"json",
                        success: function(returnData){                            
                            if(returnData.status == 200){
                                layer.alert(returnData.msg, {
                                    closeBtn: 0
                                  }, function(){
                                    layer.closeAll();  
                                    table.reload('verify_list',{}) 
                                  });
                            }else{
                                layer.alert(returnData.msg, {
                                    closeBtn: 0
                                  }, function(){
                                    layer.closeAll();  
                                  });
                            }
                        }
                      })
                    }
                  })
                  return false //开启该代码可禁止点击该按钮关闭
                }
                ,btn3: function(index, layero){
                  layer.close(layer.index);
                }

              });
              break;
        }
    })
      var $ = layui.$, active = {
        reload: function(){
          var orderNo = $('#order_no');
          var customerName = $('#customer_name');
          var username = $('#username');
            var status = $('#status');
          //执行重载
          table.reload('verify_list', {
            page: {
              curr: 1 //重新从第 1 页开始
            }
            ,where: {
              key: {
                order_no: orderNo.val(),
                customer_name: customerName.val(),
                username: username.val(),
                  status:status.val()
              }
            }
          })
        },
        reload1: function(){
          var orderNo = $('#order_no');
          var customerName = $('#customer_name');
            var status = $('#status');
          //执行重载
          table.reload('delivery_list1', {
            page: {
              curr: 1 //重新从第 1 页开始
            }
            ,where: {
              key: {
                order_no: orderNo.val(),
                customer_name: customerName.val(),
                  status:status.val()
              }
            }
          })
        },
        reload4: function(){
          var orderNo = $('#order_no');
          var customerName = $('#customer_name');
            var status = $('#status');
          //执行重载
          table.reload('delivery_list2', {
            page: {
              curr: 1 //重新从第 1 页开始
            }
            ,where: {
              key: {
                order_no: orderNo.val(),
                customer_name: customerName.val(),
                  status:status.val()
              }
            }
          })
        },
        reload2: function(){
          var orderNo = $('#order_no');
          var customerName = $('#customer_name');
          var username = $('#username');
            var status = $('#status');
          //执行重载
          table.reload('change_list1', {
            page: {
              curr: 1 //重新从第 1 页开始
            }
            ,where: {
              key: {
                order_no: orderNo.val(),
                customer_name: customerName.val(),
                username: username.val(),
                type: 1,
                  status:status.val()
              }
            }
          })
        },
        reload3: function(){
          var orderNo = $('#order_no');
          var customerName = $('#customer_name');
          var username = $('#username');
            var status = $('#status');
          //执行重载
          table.reload('change_list2', {
            page: {
              curr: 1 //重新从第 1 页开始
            }
            ,where: {
              key: {
                order_no: orderNo.val(),
                customer_name: customerName.val(),
                username: username.val(),
                type: 2,
                  status:status.val()
              }
            }
          })
        },
        add_new1: function(){
          window.location.href='/general/guojigang/public/index/delivery/index1';
        },
        add_new2: function(){
          window.location.href='/general/guojigang/public/index/delivery/index2';
        },
        reload5: function(){
          var orderNo = $('#order_no');
          var customerName = $('#customer_name');
          var username = $('#atUser');
            var status = $('#status');
          //执行重载
          table.reload('verifier', {
            page: {
              curr: 1 //重新从第 1 页开始
            }
            ,where: {
              key: {
                order_no: orderNo.val(),
                customer_name: customerName.val(),
                username: username.val(),
                  status:status.val()
              }
            }
          })
        }
      };

    layui.form.on('switch(stat1)', function (obj) {
      var state = this.checked ? 1 : 0;
      console.log("checked:" + this.checked + "state:" + state, "id:" + this.value);
      let arrayList = layui.data('jiaoqibg').obj_key;
      arrayList.forEach(item=>{
        if(item.id == this.value) {
            item['isShow'] = state;
          //更新操作
        }
      })
      layui.data('jiaoqibg', {key:'obj_key', value: arrayList});
      table.reload('add_list', {data:arrayList});
    });

    layui.form.on('switch(stat2)', function (obj) {
      var state = this.checked ? 1 : 0;
      console.log("checked:" + this.checked + "state:" + state, "id:" + this.value);
      let arrayList = layui.data('jiaoqibg2').obj_key;
      arrayList.forEach(item=>{
        if(item.id == this.value) {
            item['isShow'] = state;
          //更新操作
        }
      })
      layui.data('jiaoqibg2', {key:'obj_key', value: arrayList});
      table.reload('add_list2', {data:arrayList});
    });

    $('.layui-fluid .layui-btn').on('click', function(){
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

    //常规用法
    laydate.render({
        elem: '#ddate2',

    });

    function infoDate1(){
        var num = 0;
        let arrayList = layui.data('jiaoqibg').obj_key;
        let error = 0;
        if (arrayList.length <5) {
          layer.alert("请至少选择5条数据！！");
          return false;
        }
        arrayList.forEach(item=>{
          if(!item.deliveryDate && item.isShow == 1) {
            error = 1;    
          }
        })
        if (error == 1) {
          layer.alert("交期变更不能有空值！！");
          return false;
        }
        layer.confirm('确定提交修改吗?', {
          btn: ['提交', '取消']
        }, function () {
          num += 1;
          if (num == 1) {
             // 可发放提交
          $.ajax({
              url: addData1,
              type: "POST",
              dataType: 'json',
              contentType:'application/json',
              data: JSON.stringify(arrayList),
              success: function (res) {
                  var notFoundStr = '';
                  if(res.status === 200){
                    layui.data('jiaoqibg', {key:'obj_key', value:[]});
                    table.reload('delivery_list1', {
                      page: {
                        curr: 1 //重新从第 1 页开始
                      }
                    })
                    //显示没有添加成功的
                    if (res.data.length != 0) {
                      notFoundStr = "id: " + res.data.join(',') + " 没有找到审核人！！";
                    }  
                    if (notFoundStr != '') {
                      layer.msg(notFoundStr);
                    } else {
                      window.location.href="/general/guojigang/public/index/delivery/changeList1";                      
                    }
                  } else {
                      parent.layer.msg(res.msg, {
                          icon: 5
                      });
                  }
                }, error: function () {
                }
              });
          }
          return false;
        });
    }

    function infoDate2(){
      var num = 0;
      let arrayList = layui.data('jiaoqibg2').obj_key;
      let error = 0;
      if (arrayList.length <5) {
        layer.alert("请至少选择5条数据！！");
        return false;
      }
      arrayList.forEach(item=>{
        if(!item.deliveryDate && item.isShow == 1) {
          error = 1;    
        }
      })
      if (error == 1) {
        layer.alert("交期变更不能有空值！！");
        return false;
      }
      layer.confirm('确定提交修改吗?', {
        btn: ['提交', '取消']
      }, function () {
        num += 1;
        if (num == 1) {
          $.ajax({
            url: addData2,
            type: "POST",
            dataType: 'json',
            contentType:'application/json',
            data: JSON.stringify(arrayList),
            success: function (res) {
              var string = '';
                if(res.status === 200){
                 layui.data('jiaoqibg2', {key:'obj_key', value:[]});
                 table.reload('delivery_list2', {
                   page: {
                     curr: 1 //重新从第 1 页开始
                   }
                 })
                 window.location.href="/general/guojigang/public/index/delivery/changeList2";                      
                } else {
                    parent.layer.msg(res.msg, {
                        icon: 5
                    });
                }
            }, error: function () {
            }
          });
        }
        return false;
      });
    }

    $('#submit_xiaoshou').on('click',function(){
        infoDate1()
    });

    $('#submit_jihua').on('click',function(){
      infoDate2()
    });

    //所有交期变更单
      table.render({
        elem: '#change_list1'
        ,url: ajaxChangeList + '?type=1'
        ,limits: [10,20,50,100,200,500,1000,99999]
        ,limit: 20 //每页默认显示的数量
        ,response: {
            statusName: 'status'
            ,statusCode: 200
            ,msgName: 'msg'
            ,countName: 'count'
            ,dataName: 'data'
        }
        ,cols: [[
             {field:'delivery_id', title: 'ID', with:'100'}
            ,{field:'orderId', title: '订单ID',width:'100'}
            ,{field:'ctime', title: '创建时间', width:'180'}
            ,{field:'username', title: '填写人', width:'100'}
            ,{field:'orderNo', title: '订单编号', width:'250'}
            ,{field:'ddLeiXing', title: '订单类型', width:'100'}
            ,{field:'zhangtao', title: '账套', width:'200'}
            ,{field:'currency', title: '币种', width:'100'}
            ,{field:'cCusName', title: '客户名称', width:'260'}
            ,{field:'date1', title: '目标交期', width:'150'}
            ,{field:'atTime', title: '送达时间', width:'150'}
            ,{field:'cCusPPersonText', title: '业务员', width:'100'}
            ,{field:'delivery_date', title: '交期变更', width:'150'}
            ,{
              field:'status',
              title: '状态', 
              width:'150',
              templet: function(d) {
                var state = "";
                switch(d.status){
                  case 0:
                    state = '<strong style="color:#1E9FFF">未审核</strong>';
                    break;
                  case 1:
                    state = '<strong style="color:#f1c232">审核中</strong>';
                    break;
                  case 2:
                    state = '<strong style="color:#009688">通过</strong>';
                    break;
                  case 3:
                    state = '<strong style="color:red">不通过</strong>';
                    break;
                  default:
                    break;         
                }
                return state;
              }
            }
            ,{
              field:'isShow',
              title: '订单状态',
              templet: function (d) {
                var state = "";
                if (d.isShow == 1) {
                    state = '<strong style="color:#009688">开启</strong>';
                }
                else {
                  state = '<strong style="color:red">关闭</strong>';;
                }
                return state;
              },
              width:'100'
            }
            ,{fixed: 'right', title: '操作', templet:'#colChangeListBar', width:'220'}

        ]]
        ,id: 'change_list1'
        ,page: true
        ,toolbar:"#headDeliveryBar"
        ,text: { none: '暂无相关数据' }
        ,totalRow:true
        ,done: function (res, curr, count){
          //  $(".layui-table tr").each(function(){
          //       var text = $(this).children("td:nth-child(2)").text();
          //       text = parseInt(text);
          //       if (addedArray.indexOf(text) > -1 ){
          //           $(this).children("td:first").find('button').addClass("layui-btn-disabled").attr("disabled",true);
          //       }
          // })
                    
        }
      });

      //所有交期变更单
      table.render({
        elem: '#change_list2'
        ,url: ajaxChangeList + '?type=2'
        ,limits: [10,20,50,100,200,500,1000,99999]
        ,limit: 20 //每页默认显示的数量
        ,response: {
            statusName: 'status'
            ,statusCode: 200
            ,msgName: 'msg'
            ,countName: 'count'
            ,dataName: 'data'
        }
        ,cols: [[
             {field:'delivery_id', title: 'ID', width:'100'}
            ,{field:'orderId', title: '订单ID',width:'100'}
            ,{field:'ctime', title: '创建时间', width:'180'}
            ,{field:'username', title: '填写人', width:'100'}
            ,{field:'orderNo', title: '订单编号', width:'250'}
            ,{field:'ddLeiXing', title: '订单类型', width:'100'}
            ,{field:'zhangtao', title: '账套', width:'200'}
            ,{field:'currency', title: '币种', width:'100'}
            ,{field:'cCusName', title: '客户名称', width:'260'}
            ,{field:'date1', title: '目标交期', width:'150'}
            ,{field:'atTime', title: '送达时间', width:'150'}
            ,{field:'cCusPPersonText', title: '业务员', width:'100'}
            ,{field:'delivery_date', title: '交期变更', width:'150'}
            ,{
              field:'status',
              title: '状态', 
              width:'150',
              templet: function(d) {
                var state = "";
                switch(d.status){
                  case 0:
                    state = '<strong style="color:#1E9FFF">未审核</strong>';
                    break;
                  case 1:
                    state = '<strong style="color:#f1c232">审核中</strong>';
                    break;
                  case 2:
                    state = '<strong style="color:#009688">通过</strong>';
                    break;
                  case 3:
                    state = '<strong style="color:red">不通过</strong>';
                    break;
                  default:
                    break;         
                }
                return state;
              }
            }
            ,{
              field:'isShow',
              title: '订单状态',
              templet: function (d) {
                var state = "";
                if (d.isShow == 1) {
                    state = '<strong style="color:#009688">开启</strong>';
                }
                else {
                  state = '<strong style="color:red">关闭</strong>';;
                }
                return state;
              },
              width:'100'
            }
            ,{fixed: 'right', title: '操作', templet:'#colChangeListBar', width:'220'}

        ]]
        ,id: 'change_list2'
        ,page: true
        ,toolbar:"#headDeliveryBar"
        ,text: { none: '暂无相关数据' }
        ,totalRow:true
        ,done: function (res, curr, count){
          //  $(".layui-table tr").each(function(){
          //       var text = $(this).children("td:nth-child(2)").text();
          //       text = parseInt(text);
          //       if (addedArray.indexOf(text) > -1 ){
          //           $(this).children("td:first").find('button').addClass("layui-btn-disabled").attr("disabled",true);
          //       }
          // })
                    
        }
      });

      //一些事件监听
    element.on('tab(docDemoTabBrief)', function(data){
      var map = [1,2,3,0];
      var status = map[data.index];
      table.reload('verify_list', {
        page: {
          curr: 1 //重新从第 1 页开始
        }
        ,where: {
          key: {
            status: status
          }
        }
        
      })
      if(data.index != 0){
        $("#batch_verify").addClass("layui-btn-disabled").attr("disabled",true);
        // $(".layui-table-header").find("input[name ='layTableCheckbox'][lay-filter='layTableAllChoose']").each(function(d) {
        //   $(this).attr("disabled", 'disabled');
        //   form.render('checkbox');
        // });
        // $(".layui-table-body.layui-table-main").find("input[name='layTableCheckbox']").each(function() {
        //     $(this).attr("disabled", 'disabled');
        //     form.render('checkbox');
        // });
      }
      
    });

    element.on('tab(docDemoTabBrief2)', function(data){
      table.reload('verifier', {
        page: {
          curr: 1 //重新从第 1 页开始
        }
        ,where: {
            type: data.index + 1
        }
        
      })
    });


      //我的审核列表
      table.render({
        elem: '#verify_list'
        ,url: ajaxVerifyList
        ,limits: [10,20,50,100,200,500,1000,99999]
        ,limit: 20 //每页默认显示的数量
        ,response: {
            statusName: 'status'
            ,statusCode: 200
            ,msgName: 'msg'
            ,countName: 'count'
            ,dataName: 'data'
        }
        ,cols: [[
             {checkbox: true}
            ,{field:'verify_id', title: '流程号', width: '150', sort:'true', hide:'true'}
            ,{field:'orderNo', title: '订单编号', width:'170', sort:'true'}
            // ,{field:'delivery_id', title: '变更单号', width:'100', sort:'true'}
            ,{field:'zhangtao', title: '账套', width:'120', sort:'true'}
            ,{field:'ddLeiXing', title: '类型', width:'80', sort:'true'}
            ,{field:'categories', title: '产品类别', width:'150', sort:'true'}
            ,{field:'country', title: '国家', width:'80', sort:'true'}
            ,{field:'customer', title: '客户简称', width:'200', sort:'true'}
            ,{field:'ctime', title: '变更日期', width:'180', sort:'true'}
            // ,{field:'atTime', title: '送达时间', width:'200', sort:'true'}
            ,{field:'username', title: '发起人', width:'100', sort:'true'}
            ,{field:'cCusPPersonText', title: '业务员', width:'100', sort:'true'}
            ,{field:'date2', title: '原确认交期', width:'120', sort:'true'}
            ,{field:'delivery_date', title: '新确认交期', width:'120', sort:'true'}
            ,{
              field:'odlIsShow',
              title: '原订单状态',
              templet: function (d) {
                var state = "";
                if (d.oldIsShow == 1) {
                  state = '<strong style="color:#009688">开启</strong>';
                }
                else {
                  state = '<strong style="color:red">关闭</strong>';;
                }
                return state;
              },
              width:'120',
              sort:'true'
            }
            ,{
              field:'isShow',
              title: '新订单状态',
              templet: function (d) {
                var state = "";
                if (d.isShow == 1) {
                  state = '<strong style="color:#009688">开启</strong>';
                }
                else {
                  state = '<strong style="color:red">关闭</strong>';;
                }
                return state;
              },
              width:'120',
              sort:'true'
            }
            // ,{
            //   field:'changeStatus',
            //   title: '变更单状态',
            //   width:'150',
            //   sort:'true',
            //   templet: function (d) {
            //     var state = "";
            //     if (d.changeStatus == 0) {
            //         state = '<strong style="color:#1E9FFF">未审核</strong>';;
            //     } else if(d.changeStatus == 1){
            //         state = '<strong style="color:#f1c232">审核中</strong>';
            //     } else if(d.changeStatus == 2) {
            //         state = '<strong style="color:#009688">通过</strong>';
            //     } else if(d.changeStatus == 3) {
            //         state = '<strong style="color:red">不通过</strong>';
            //     } else {
            //         state = "";
            //     }
            //     return state;
            //   }
            // }
            // ,{field:'status', title: '审核状态', templet:'#typeTpl', width:'150', sort:'true'}
            ,{fixed: 'right',title: '操作', templet:'#colVerifyListBar', width:'200'}

        ]]
        ,id: 'verify_list'
        ,page: true
        ,toolbar:"#headDeliveryBar1"
        ,text: { none: '暂无相关数据' }
        ,totalRow:true
        ,done: function (res, curr, count){
          let data = res.data;
          if (data.length == 0 || data[0].status != 0){
            
          } 
          
          
        }
      });
    var whereVerify = {key:{privilege: 1}};
      if (bgStatus && orderNo){
        $("#order_no").val(orderNo);
        whereVerify = {type:bgStatus, key:{privilege: 1, order_no: orderNo}};
      }
      //所有交期变更单
     table.render({
      elem: '#verifier'
      ,url: ajaxChangeList
      ,limits: [10,20,50,100,200,500,1000,99999]
      ,limit: 20 //每页默认显示的数量
      ,where: whereVerify
      ,response: {
          statusName: 'status'
          ,statusCode: 200
          ,msgName: 'msg'
          ,countName: 'count'
          ,dataName: 'data'
      }
      ,cols: [[
           {field:'delivery_id', title: 'ID'}
          ,{field:'orderId', title: '订单ID', width:'100'}
          ,{field:'ctime', title: '创建时间', width:'180'}
          ,{field:'username', title: '填写人', width:'100'}
          ,{field:'orderNo', title: '订单编号', width:'250'}
          ,{field:'ddLeiXing', title: '订单类型', width:'100'}
          ,{field:'zhangtao', title: '账套', width:'200'}
          ,{field:'currency', title: '币种', width:'100'}
          ,{field:'cCusName', title: '客户名称', width:'260'}
          ,{field:'date1', title: '目标交期', width:'150'}
          ,{field:'atTime', title: '送达时间', width:'150'}
          ,{field:'cCusPPersonText', title: '业务员', width:'100'}
          ,{field:'delivery_date', title: '交期变更', width:'150'}
          ,{
            field:'status',
            title: '状态', 
            width:'150',
            templet: function(d) {
              var state = "";
              switch(d.status){
                case 0:
                  state = '<strong style="color:#1E9FFF">未审核</strong>';
                  break;
                case 1:
                  state = '<strong style="color:#f1c232">审核中</strong>';
                  break;
                case 2:
                  state = '<strong style="color:#009688">通过</strong>';
                  break;
                case 3:
                  state = '<strong style="color:red">不通过</strong>';
                  break;
                default:
                  break;         
              }
              return state;
            }
          }
          ,{
            field:'isShow',
            title: '订单状态',
            templet: function (d) {
              var state = "";
              if (d.isShow == 1) {
                  state = '<strong style="color:#009688">开启</strong>';
              }
              else {
                state = '<strong style="color:red">关闭</strong>';;
              }
              return state;
            },
            width:'100'
          }
          ,{title: '操作', templet:'#colChangeListBar', width:'220'}

      ]]
      ,id: 'verifier'
      ,page: true
      ,toolbar:"#headDeliveryBar"
      ,text: { none: '暂无相关数据' }
      ,totalRow:true
      ,done: function (res, curr, count){  
      }
    });
    
    
      // 设置最小可选的日期
      function minDate(){
        var now = new Date();
        var month= now.getMonth()+1;
        month= month<10?('0'+month):month; 
        var day=now.getDate();
        day=day<10?('0'+day):day; //替换2019-1-1为2019-01-01
        console.log(now.getFullYear()+"-" +month+ "-" + day);
        return now.getFullYear()+"-" +month+ "-" + day;
      } 
      //以复选框选择提交审核
      table.on('checkbox(user)', function(obj){
        console.log(obj)
      });

      

      

});


